<template>
<div>
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
        <el-button type="primary">添加角色</el-button>
        <el-table :data="rolesList" row-key="id">
            <el-table-column type="expand" label="展开">
              <template slot-scope="scope">
                <el-row v-for="item1 in scope.row.children" :key="item1.id" style="background-color:#e5e5eb;margin-bottom:20px;padding-top:10px;">
                  <el-col :span="5">
                    <el-tag type="primary" closable>{{item1.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <div v-for="item2 in item1.children" :key="item2.id" style="background-color:#c9bbc2;margin-bottom:10px;">
                      <el-row>
                        <el-col :span="5">
                          <el-tag type="warning" closable>{{item2.authName}}</el-tag>
                          <i class="el-icon-caret-right"></i>
                        </el-col>
                        <el-col :span="19">
                          <el-tag @close="delRightsFn(scope.row,item3.id)" v-for="item3 in item2.children" :key="item3.id" type="danger" closable>{{item3.authName}}</el-tag>
                        </el-col>
                      </el-row>
                    </div>

                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="roleName" label="角色名称"></el-table-column>
            <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
            <el-table-column label="操作">
              <!-- eslint-disable-next-line -->
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" icon="el-icon-edit" ></el-button>
                    <el-button type="danger" size="mini" icon="el-icon-delete"></el-button>
                    <el-tooltip content="分配权限" placement="top" :enterable="false">
                        <el-button type="warning" size="mini" icon="el-icon-setting" @click="showRightDialogFn(scope.row)"></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="rightDialogVisible"
      width="30%">
      <!-- node-key我们根据这个来确定哪些选中 -->
      <el-tree ref="mytree" :default-checked-keys="selectedKeys" node-key="id" default-expand-all show-checkbox :data="rightsList" :props="defaultProps"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRights">确 定</el-button>
      </span>
    </el-dialog>
</div>
</template>

<script>
// 1. 只需要关心三级权限
// 2. 有两种UI效果 全选 半选
// 把当前这一行记录所有的三级权限对应的id值收集到一个数组当中
export default {
  created () {
    this.getRolesList()
  },
  data () {
    return {
      rolesList: [],
      rightDialogVisible: false,
      rightsList: [],
      defaultProps: {
        label: 'authName'
      },
      selectedKeys: [],
      roleId: null// 我们在显示权限对话框的时候，可以把当前要改的角色id值存起来，我们将来在点击保存的时候要用
    }
  },
  methods: {
    async getRolesList () {
      const {
        data: res
      } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.message.error('查询失败')
      console.log(res)
      this.rolesList = res.data
    },
    delRightsFn (role, id) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${id}`)
        if (res.meta.status !== 200) return this.message.error('删除失败')
        console.log(res)
        role.children = res.data
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async showRightDialogFn (role) {
      this.roleId = role.id
      this.rightDialogVisible = true
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.message.error('获取失败')
      this.rightsList = res.data

      // const arr = []// 收集所有的三级权限的id值
      // if (role.children.length > 0) {
      //   role.children.forEach(item1 => {
      //     if (item1.children.length > 0) {
      //       item1.children.forEach(item2 => {
      //         if (item2.children.length > 0) {
      //           item2.children.forEach(item3 => {
      //             arr.push(item3.id)
      //           })
      //         }
      //       })
      //     }
      //   })
      // }

      // this.selectedKeys = arr

      // 递归 当你做的事情在重复并且嵌套 不确定 10层 100层
      const arr = []
      function fn (obj) {
        if (obj.children) {
          obj.children.forEach(item => {
            fn(item)
          })
        } else {
          // 最底层
          arr.push(obj.id)
        }
      }
      fn(role)
      this.selectedKeys = arr
    },
    async saveRights () {
      const arr = [...this.$refs.mytree.getCheckedKeys(), ...this.$refs.mytree.getHalfCheckedKeys()]
      // arr.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: arr.join(',') })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新权限失败')
      this.$message.success('更新权限成功')
      this.rightDialogVisible = false // 关闭对话框
      this.getRolesList()// 数据变旧了，需要重新更新一下
    }
  },
  computed: {

  }
}
// 用户 角色 权限
</script>

<style scoped>
.el-tag{
  margin:20px;
}
</style>
